import cheerio from "cheerio";
import fs from "fs";
import {Analyzer} from "./crawler";

interface Course {
  title: string;
  count: number;
}

interface CourseResult {
  time: number;
  data: Course[];
}

interface Content {
  [propName: number]: Course[]
}

export default class DellAnalyzer implements Analyzer {

  private static instance: DellAnalyzer

  private constructor() {
  }

  static getInstance() {
    if (!DellAnalyzer.instance) {
      DellAnalyzer.instance = new DellAnalyzer();
    }
    return DellAnalyzer.instance;
  }

  private getCourseInfo(html: string) {
    const courseInfos: Array<Course> = [];
    const $ = cheerio.load(html);
    const courseItems = $('.course-item');
    courseItems.map((index, item) => {
      const descs = $(item).find('.course-desc');
      const title = descs.eq(0).text();
      const count = parseInt(descs.eq(1).text().split('：')[1]);
      courseInfos.push({
        title, count
      })
    })
    const result = {
      time: new Date().getTime(),
      data: courseInfos
    }
    return result;
  }

  generateJSONContent(info: CourseResult, filePath: string) {
    let fileContent: Content = {};
    if (fs.existsSync(filePath)) {
      fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    }
    fileContent[info.time] = info.data;
    return JSON.stringify(fileContent);
  }

  public analyze(html: string, filePath: string) {
    const courseInfo = this.getCourseInfo(html);
    const content = this.generateJSONContent(courseInfo, filePath);
    return content;
  }
}
